13. addEventListener

addEventListener

The Browser's Event System

The browser has an event system that announces everything you do on the page. An important step in learning how frameworks handle user interaction is to understand this event system and how developers can hook into it.

The addEventListener method is an incredibly important part of the DOM API. This method allows you to listen in on the browser's event system. Here's its signature:

target.addEventListener( type, listener );

The target can be anything that implements the EventTarget interface. This could be element on the page, the document object, the window object, even an XHR object. addEventListener can be used as a hook on any of these elements to listen in on the events that are occurring on them.

The type is a string of the kind of event addEventListener will listen for. An example might be click, animationend, or keyup. Make sure to look through the list of standard events.

The listener is anything that implements the EventListener interface or just a function.

For example:

document.addEventListener( 'keydown', function () {
    console.log( 'A keyboard button was pressed.' );
});

or

document.querySelector('#orderForm').addEventListener( 'submit', function () {
    console.log( 'The form has been submitted.' );
});

Event Object

What if we wanted to set up an event listener to listen for when the escape key is pressed, verify the contents in a form before it is sent to the server, or check the status of an XHR call? The browser passes an event object when it calls the listener function. We can use this event object to gather information about the event that occurred.

If we want to listen for when the escape key is pressed we would use the event object:

document.addEventListener( 'keydown', function ( eventObject ) {
    if (eventObject.keyCode == 27) {
        // the escape key was pressed
    }
});

Custom Events

The type of event we've looked at so far are the standard events that are built into the browser. What if we wanted to create our own kind of event, like the partyTime event? We use the CustomEvent API to do this!

// create the custom `partyTime` event
var myCustomEvent= new CustomEvent( 'partyTime', {timeToParty: true, partyYear: 1999} );

// listen to the `document` for the `partyTime` event
document.addEventListener('partyTime', function(evt) {
    if (evt.partyYear) {
        console.log( "Partying like it's " + evt.partyYear + "!");
    }

    document.body.style.backgroundImage = 'linear-gradient(90deg, orange, blue)';
});

// trigger the custom event
document.dispatchEvent( myCustomEvent );

The browser's event system, addEventListener, and custom events give us a ton of power in dealing with interactions and events that occur in our web apps.

Further Research